package com.cheng.gmall.item.service.impl;

import com.alibaba.fastjson.JSON;
import com.cheng.gmall.common.config.constant.RedisConst;
import com.cheng.gmall.item.service.CacheService;
import com.cheng.gmall.product.vo.SkuDetailVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

/**
 * @author Cheng-02
 * @version V1.0
 * @Package com.cheng.gmall.item.service.impl
 * @date 2024/5/30 下午5:35
 */
@Slf4j
@Service
public class CacheServiceImpl implements CacheService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public SkuDetailVo getFromCache(Long skuId) {
        log.info("正在查询缓存...");
        //1、查询缓存
        String json = redisTemplate.opsForValue().get(RedisConst.SKU_DETAIL_CACHE + skuId);
        //缓存没有
        if (StringUtils.isEmpty(json)) {
            return null;
        } else if ("x".equals(json)) {
            return new SkuDetailVo(); //返回空对象
        } else {
            log.info("缓存命中");
            return JSON.parseObject(json, SkuDetailVo.class);
        }
    }


    @Override
    public void saveData(Long skuId, Object returnVal) {
        String jsonString = "x";  //默认是x
        if (returnVal != null) {
            jsonString = JSON.toJSONString(returnVal); //真正json
        }
        redisTemplate.opsForValue().set(RedisConst.SKU_DETAIL_CACHE + skuId, jsonString, 7, TimeUnit.DAYS);
    }

    //从缓存中获取指定类型的数据
    @Override
    public Object getCacheData(String key, Type returnType) {
        //1、查询缓存
        String json = redisTemplate.opsForValue().get(key);
        //缓存没有
        if (StringUtils.isEmpty(json)) {
            return null;
        } else if ("x".equals(json)) {
            //返回空对象
            return new Object();
        } else {
            log.info("缓存命中");
            return JSON.parseObject(json, returnType);
        }
    }

    @Override
    public boolean mightContain(String bitMapName, Long bitMapIndex) {
        return redisTemplate.opsForValue().getBit(bitMapName, bitMapIndex);
    }

    @Override
    public void saveCacheData(String cachekey, Object o, long ttl, TimeUnit unit) {
        String jsonString = "x";  //默认是x
        if (cachekey != null) {
            jsonString = JSON.toJSONString(cachekey); //真正json
        }
        redisTemplate.opsForValue().set(cachekey, jsonString, ttl, unit);
    }


}
